package com.gitee.blowforcesquad.dosportsandroid.http;

import com.gitee.blowforcesquad.dosports.http.api.DoSportsApi;
import com.gitee.blowforcesquad.dosports.http.interceptor.TokenInterceptor;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by lirenhao on 2017/11/26.
 */
public class Api {

    private static final String BASE_URL = "";

    private static final int DEFAULT_CONNECT_TIMEOUT = 6;
    private static final int DEFAULT_READ_TIMEOUT = 6;
    private static final int DEFAULT_WRITE_TIMEOUT = 6;

    private static final HttpLoggingInterceptor.Level LOG_LEVEL = HttpLoggingInterceptor.Level.BODY;

    private static Retrofit RETROFIT;

    private static Retrofit getRetrofit() {
        if (RETROFIT == null) {
            OkHttpClient okHttpClient = initOkHttpClient();
            RETROFIT = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .client(okHttpClient)
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return RETROFIT;
    }

    private static OkHttpClient initOkHttpClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();

        HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor();
        logInterceptor.setLevel(LOG_LEVEL);

        TokenInterceptor tokenInterceptor = new TokenInterceptor();

        builder.connectTimeout(DEFAULT_CONNECT_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(DEFAULT_READ_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(DEFAULT_WRITE_TIMEOUT, TimeUnit.SECONDS)
                .addInterceptor(logInterceptor)
                .addInterceptor(tokenInterceptor);

        return builder.build();
    }

    public DoSportsApi getDoSportsApi() {
        return getRetrofit().create(DoSportsApi.class);
    }
}
